<?php

namespace App\Service\Index;

use App\Constants\ErrorCode;
use App\Model\CallBase;
use App\Model\User;
use App\Model\UserProfile;
use App\Model\VoiceCall;
use App\Service\CallBaseService;

/**
 * 拨打语音电话
 */
class VoiceCallService extends CallBaseService
{
    public function handle()
    {
        //自己的ID
        $userId = $this->getUserId();
        //主播用户ID
        $hostUserId = $this->request->input('host_user_id', 0);
        //呼叫来源
        $callFrom = $this->request->input('from', 0);
        //不能打给自己
        if ($userId == $hostUserId) return $this->setError(ErrorCode::PARAMETER_ERROR, '不能拨打给自己~');

        //天天福利
        if (CallBase::FROM_DAILY_FREE == $callFrom) {
            return $this->dailyFreeCall($userId, VoiceCall::class);
        }


        //被叫方
        if (User::checkOfficial($hostUserId)) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '暂无法拨打给小助手~');
        }
        //主播呼叫
        $selfProfile = UserProfile::getProfile($userId);
//        if (UserProfile::checkRoleHost($selfProfile->role)) {
//            return $this->fromHostCall($userId, $hostUserId, VoiceCall::class, $selfProfile);
//        }

        if ($selfProfile->gender == 0) {
            if ($selfProfile->avatar_vrfy == 1) {
                return $this->fromHostCall($userId, $hostUserId, VoiceCall::class, $selfProfile);
            } else {
                return $this->setError(ErrorCode::REAL_AVATAR_NOT_VRFY, '还未通过真人头像认证～');
            }
        }

        //非小助手呼叫
        if (!User::checkOfficial($userId)) {
            //检测拨打权限
            $checkResult = $this->checkCall($userId, $hostUserId, VoiceCall::CALL_TYPE);
            if ($checkResult['ret'] != 0) return $checkResult;
            $coinSetting = $checkResult['hostCoinSetting'];
            $hostProfile = $checkResult['hostProfile'];
        }else{
            $coinSetting = 0;
            $hostProfile = UserProfile::getProfile($hostUserId);
        }

        //修改以前无效状态
        VoiceCall::finishOldCall($userId);
        //加记录
        VoiceCall::addRecord($userId, $hostUserId, CallBase::FROM_MAIN, $coinSetting);
        //呼叫回调
        $this->callHook($hostUserId, $userId, VoiceCall::CALL_TYPE);
        return [
            'permit' => 1,
            'user_info' => UserProfile::buildHostItem($hostProfile)
        ];
    }
}
